package com.example.myapplication.found;

import com.example.myapplication.found.bean.BuyPointBean;
import com.example.myapplication.found.bean.FoundBean;
import com.example.myapplication.found.bean.KDJOrderBean;
import com.example.myapplication.found.bean.StockOrderBean;
import com.example.myapplication.found.bean.ZhangDieBean;
import com.example.myapplication.found.contract.KdjLoopCallback;
import com.example.myapplication.found.model.DaBan;
import com.example.myapplication.found.model.Fenxi0;
import com.example.myapplication.found.model.Fenxi;
import com.example.myapplication.found.model.Fenxi10;
import com.example.myapplication.found.model.Fenxi12;
import com.example.myapplication.found.model.Fenxi13;
import com.example.myapplication.found.model.Fenxi2;
import com.example.myapplication.found.model.Fenxi3;
import com.example.myapplication.found.model.Fenxi4;
import com.example.myapplication.found.model.Fenxi5;
import com.example.myapplication.found.model.Fenxi6;
import com.example.myapplication.found.model.Fenxi7;
import com.example.myapplication.found.model.Fenxi8;
import com.example.myapplication.found.model.Fenxi9;
import com.example.myapplication.found.model.KDJ;
import com.example.myapplication.found.model.Point;
import com.example.myapplication.shortvideo.utils.GsonUtil;
import com.example.myapplication.found.contract.SimpleCallback;
import com.google.gson.reflect.TypeToken;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * @author: rongfeng
 * @date: 2022/2/10
 * @description
 */
public class IndustryFound {
    List<FoundBean> foundList = new ArrayList<>();
    ExecutorService pool;
    static volatile AtomicInteger index = new AtomicInteger(0);

    static volatile AtomicInteger endNum = new AtomicInteger(0);

    public static int tstType = KDJ.type;
    public static boolean isTest = true;
    public static boolean isUpdateData = false;
    public static Set<String> date = new HashSet<>();

    public static int lmt = 250 * 5;
    String url_300 = "http://90.push2.eastmoney.com/api/qt/clist/get?cb=jQuery1124015506542369878207_1645716770136&pn=1&pz=300&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid=f3&fs=b:BK0500+f:!50&fields=f12,f13,f14&_=1645716770154";
    String url_180 = "https://push2.eastmoney.com/api/qt/clist/get?cb=jQuery112303263302413118838_1645671853224&fid=f62&po=1&pz=200&pn=1&np=1&fltt=2&invt=2&ut=b2884a393a59ad64002292a3e90d46a5&fs=b%3ABK0612&fields=f12,f13,f14";
    String url_hangye = "http://36.push2.eastmoney.com/api/qt/clist/get?cb=jQuery112407532789864795488_1644476578201&pn=1&pz=200&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid=f3&fs=m:90+t:2+f:!50&fields=f12,f13,f14&_=" + System.currentTimeMillis();
    String url_shangzhen = "http://91.push2.eastmoney.com/api/qt/clist/get?cb=jQuery112403142443920852831_1645715205203&pn=1&pz=10000&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid=f20&fs=m:1+t:2,m:1+t:23&fields=f12,f13,f14,f20&_=1645715205294";
    String url_shengzhen = "https://37.push2.eastmoney.com/api/qt/clist/get?cb=jQuery1124039943190116139937_1645779414724&pn=1&pz=10000&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid=f3&fs=m:0+t:6,m:0+t:80&fields=f12,f13,f14,f20&_=1645779414733";

    public String url_hangye_list = "https://72.push2.eastmoney.com/api/qt/clist/get?cb=jQuery11240797026970623131_1646049374402&pn=1&pz=10000&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid=f3&fs=b:%s+f:!50&fields=f12,f13,f14&_=1646049374414";

    String sh_etf = "http://93.push2.eastmoney.com/api/qt/clist/get?cb=jQuery112408116331549432043_1662451090854&pn=1&pz=200&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&wbp2u=|0|0|0|web&fid=f3&fs=b:MK0839&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152&_=1662451090856";

    String sz_etf = "http://93.push2.eastmoney.com/api/qt/clist/get?cb=jQuery112408116331549432043_1662451090854&pn=1&pz=200&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&wbp2u=|0|0|0|web&fid=f3&fs=b:MK0840&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152&_=1662451090869";

    public static void main(String[] args) throws Exception {
        Point.isTest = true;
        Stock.isTest = true;
        isTest = true;
        IndustryFound industryFound = new IndustryFound();
        industryFound.getStockList(industryFound.url_hangye);
//        industryFound.getStockList(industryFound.sh_etf);
//        industryFound.start2();
//        industryFound.start();
    }

    public IndustryFound() {
        pool = Executors.newFixedThreadPool(5);
    }

    public void start() {
//        if (foundList.size() > 80) {
//            testModel();
//            for (int i = 0; i < 5; i++) {
                testModel();
//            }
//        }
    }


    private synchronized void testModel() {
        pool.execute(new Runnable() {
            @Override
            public synchronized void run() {
                int newValue1 = index.incrementAndGet();
//                System.out.print(" " + newValue1);
                if (newValue1 <= foundList.size()) {
                    FoundBean item = foundList.get(newValue1 - 1);
                    Stock stock = new Stock(item);
                    stock.setSimpleCallback(simpleCallback);
                    stock.start();
                } else {
                    synchronized (IndustryFound.class) {
//                        int ss = endNum.incrementAndGet();
//                        if (ss < 5) {
//                            return;
//                        }
//                        endNum.set(0);
                        index.set(0);
                        switch (tstType) {
                            case 1:
                                analysis1();
                                break;
                            case 3:
                                analysis1();
                                break;
                            case 4:
                                analysis4();
                                break;
                            case 5:
                                analysis1();
                                break;
                            case 6:
                                analysis6_1();
                                break;
                            case 7:
                                analysis1();
                                analysis7();
                                break;
                            case 9:
                                DaBan.analysis();
                                break;
                            case 10:
                                Fenxi2.analysis();
                                break;
                            case 11:
                                Fenxi3.analysis();
                                break;
                            case 12:
                                Fenxi4.analysis();
                                break;
                            case 13:
                                Fenxi5.analysis();
                                break;
                            case 14:
                                Fenxi6.analysis();
                                break;
                            case 15:
                                Fenxi7.analysis();
                                if (Fenxi7.rangeIndex < Fenxi7.rangeList.size()) {
                                    start();
                                }
                                break;
                            case Fenxi0.type:
                                Fenxi0.analysis();
                                if (Fenxi0.rangeIndex.incrementAndGet() < Fenxi0.rangeList.size() - 1) {
                                    start();
                                } else if (Fenxi0.huanShouIndex.incrementAndGet() < Fenxi0.rangeHuanShou.size() - 1) {
                                    Fenxi0.rangeIndex.set(0);
                                    start();
                                } else {
//                                    Fenxi0.analysisEnd();
                                }
                                break;
                            case Fenxi8.type:
                                Fenxi8.analysis();
                                if (Fenxi8.rangeIndex < Fenxi8.rangeList.size()) {
                                    start();
                                }
                                break;
                            case Fenxi9.type:
                                Fenxi9.analysis();
                                if (Fenxi9.rangeIndex < Fenxi9.rangeList.size()) {
                                    start();
                                }
                                break;
                            case Fenxi10.type:
                                Fenxi10.analysis();
                                if (Fenxi10.rangeIndex < Fenxi10.rangeList.size()) {
                                    start();
                                }
                                break;
                            case Fenxi12.type:
                                Fenxi13 fenxi13 = new Fenxi13();
                                fenxi13.start(foundList);
                                if (Fenxi13.dateIndex.decrementAndGet() > 0) {
                                    Fenxi12.mRangResult.clear();
                                    start();
                                }
                                break;
                        }
                    }
                }
            }


        });
    }

    private void analysis9() {
        System.out.println(DaBan.shouPanCount);
    }

    private void analysis7() {
        Iterator<Map.Entry<Integer, Float>> it1 = chgMap.entrySet().iterator();
        while (it1.hasNext()) {
            Map.Entry<Integer, Float> entry = it1.next();
            System.out.println("周: " + entry.getKey() + "  涨跌： " + entry.getValue());
        }
    }


    public void analysis6_1() {
        System.out.println("A股所有股票每日涨跌统计");
        System.out.println("退市股票数量：" + Fenxi.tuishiTotal);
        System.out.println("统计开始日期： " + Fenxi.startDate + " 截止日期：" + "2022-07-29");
        System.out.println("统计股票数量：" + Fenxi.stockTotal + " 支");
        System.out.println("总统计次数：" + Fenxi.lineTotal);
        System.out.println();
        System.out.println("周一上涨次数：" + Fenxi.week1.zhang + " 下跌次数：" + Fenxi.week1.die + " 平盘次数 " + Fenxi.week1.henpan +
                " 上涨比例：" + (Fenxi.week1.zhang / (float) Fenxi.week1.lines) + "%" +
                " 平均涨跌幅: " + (Fenxi.week1.chg / Fenxi.week1.lines) + "%");
        System.out.println("周二上涨次数：" + Fenxi.week2.zhang + " 下跌次数：" + Fenxi.week2.die + " 平盘次数 " + Fenxi.week2.henpan +
                " 上涨比例：" + (Fenxi.week2.zhang / (float) Fenxi.week2.lines) + "%" +
                " 平均涨跌幅: " + (Fenxi.week2.chg / Fenxi.week2.lines) + "%");
        System.out.println("周三上涨次数：" + Fenxi.week3.zhang + " 下跌次数：" + Fenxi.week3.die + " 平盘次数 " + Fenxi.week3.henpan +
                " 上涨比例：" + (Fenxi.week3.zhang / (float) Fenxi.week3.lines) + "%" +
                " 平均涨跌幅: " + (Fenxi.week3.chg / Fenxi.week3.lines) + "%");
        System.out.println("周四上涨次数：" + Fenxi.week4.zhang + " 下跌次数：" + Fenxi.week4.die + " 平盘次数 " + Fenxi.week4.henpan +
                " 上涨比例：" + (Fenxi.week4.zhang / (float) Fenxi.week4.lines) + "%" +
                " 平均涨跌幅: " + (Fenxi.week4.chg / Fenxi.week4.lines) + "%");
        System.out.println("周五上涨次数：" + Fenxi.week5.zhang + " 下跌次数：" + Fenxi.week5.die + " 平盘次数 " + Fenxi.week5.henpan +
                " 上涨比例：" + (Fenxi.week5.zhang / (float) Fenxi.week5.lines) + "%" +
                " 平均涨跌幅: " + (Fenxi.week5.chg / Fenxi.week5.lines) + "%");
        System.out.println("周六上涨次数：" + Fenxi.week6.zhang + " 下跌次数：" + Fenxi.week6.die + " 平盘次数 " + Fenxi.week6.henpan +
                " 上涨比例：" + (Fenxi.week6.zhang / (float) Fenxi.week6.lines) + "%" +
                " 平均涨跌幅: " + (Fenxi.week6.chg / Fenxi.week6.lines) + "%");
        System.out.println("周日上涨次数：" + Fenxi.week7.zhang + " 下跌次数：" + Fenxi.week7.die + " 平盘次数 " + Fenxi.week7.henpan +
                " 上涨比例：" + (Fenxi.week7.zhang / (float) Fenxi.week7.lines) + "%" +
                " 平均涨跌幅: " + (Fenxi.week7.chg / Fenxi.week7.lines) + "%");

        System.out.println();
        System.out.println("总上涨次数：" + (Fenxi.week1.zhang + Fenxi.week2.zhang + Fenxi.week3.zhang + Fenxi.week4.zhang + Fenxi.week5.zhang + Fenxi.week6.zhang + Fenxi.week7.zhang) +
                " 下跌次数：" + (Fenxi.week1.die + Fenxi.week2.die + Fenxi.week3.die + Fenxi.week4.die + Fenxi.week5.die + Fenxi.week6.die + Fenxi.week7.die) +
                " 平盘次数 " + (Fenxi.week1.henpan + Fenxi.week2.henpan + Fenxi.week3.henpan + Fenxi.week4.henpan + Fenxi.week5.henpan + Fenxi.week6.henpan + Fenxi.week7.henpan) +
                " 上涨比例：" + (Fenxi.week1.zhang + Fenxi.week2.zhang + Fenxi.week3.zhang + Fenxi.week4.zhang + Fenxi.week5.zhang + Fenxi.week6.zhang + Fenxi.week7.zhang) / (float) Fenxi.lineTotal + "%" +
                " 平均涨跌幅: " + (Fenxi.week1.chg + Fenxi.week2.chg + Fenxi.week3.chg + Fenxi.week4.chg + Fenxi.week5.chg + Fenxi.week6.chg + Fenxi.week7.chg) / (float) Fenxi.lineTotal + "%");
    }

    public void analysis6() {
        DecimalFormat decimalFormat = new DecimalFormat("0.0000");//构造方法的字符格式这里如果小数不足2位,会以0补足.
        int zhang = 0, die = 0;
        float lastChg = 0;
        List<Float> chgList = new ArrayList<>();
        for (ZhangDieBean bean : zhangDieBeans) {
            zhang = zhang + bean.zhang;
            die = die + bean.die;
            lastChg = Float.parseFloat((new BigDecimal(decimalFormat.format(lastChg))).add(new BigDecimal(decimalFormat.format(bean.lastChg))).toString());
            chgList.addAll(bean.chgList);
        }

        String p1 = decimalFormat.format((lastChg / (zhang + die)));
        String p2 = decimalFormat.format(((float) zhang) / (zhang + die) * 100);
        String p3 = decimalFormat.format(Fenxi.median(chgList));

        System.out.println("涨 " + zhang + " 跌 " + die + " 比率 " + p2 + "% 涨幅 " + p1 + "  中位数 " + p3);
    }

    public void analysis4() {
        float count = 0;
        for (Float money : moneyList
        ) {
            count = count + money;
        }
        System.out.println("最终平均金额 " + count / moneyList.size());
    }


    public void analysis3() {
        float count = 0;
        for (int day : dealDayList
        ) {
            count = count + day;
        }
        System.out.println("交易天数 " + count);
    }


    public void analysis1() {
        if (mOrderList.size() > 0) {
            float orderZhang = 0, orderDie = 0, orderPin = 0, orderAvg = 0;
            double money = 0;
            int dealDay=0;
            for (StockOrderBean orderBean : mOrderList) {
                if (orderBean.zhang) {
                    orderZhang++;
                }
                if (orderBean.die) {
                    orderDie++;
                }
                if (orderBean.pin) {
                    orderPin++;
                }
                orderAvg = orderAvg + orderBean.average;
                money = money + orderBean.money;
                dealDay += orderBean.dealDay;
            }

            System.out.println();

            Collections.sort(industryOrderList, new Comparator<KDJOrderBean>() {
                @Override
                public int compare(KDJOrderBean o1, KDJOrderBean o2) {
                    float diff = o1.moneyAvg - o2.moneyAvg;
                    if (diff > 0) {
                        return -1;
                    } else if (diff < 0) {
                        return 1;
                    }
                    return 0; //相等为0
                }
            });

            System.out.println("排序-----------------------------------开始 ");
            System.out.println();

            for (KDJOrderBean orderBean : industryOrderList) {
//                if (orderBean.orderList.size() > 10) {
                System.out.println(orderBean.name + " " + orderBean.code);
                System.out.println("买入次数 " + orderBean.orderList.size());
                System.out.println("买入涨 " + orderBean.orderZhang + " 跌 " + orderBean.orderDie + "  平 " + orderBean.orderPin + " 胜率 " + orderBean.rate + "%");
                System.out.println("平均剩余金额 " + orderBean.moneyAvg);



                System.out.println();
//                }
            }
            System.out.println("排序-----------------------------------结束 ");


            System.out.println();
            System.out.println("买入涨 " + orderZhang + " 跌 " + orderDie + "  平 " + orderPin + " 胜率 " + (orderZhang / mOrderList.size()) * 100 + "%");
            System.out.println("买入次数 " + mOrderList.size());
            System.out.println("买入次数(去重) " + IndustryFound.date.size());
            System.out.println("平均金额 " + (long) money / mOrderList.size());
            System.out.println("平均交易天数 " +  dealDay / mOrderList.size());

            System.out.println();

            orderZhang = 0;
            orderDie = 0;
            orderPin = 0;
            orderAvg = 0;
            int cishu = 0;
//            System.out.println("子股");
//            for (KDJOrderBean orderBean1 : industryOrderList) {
//                for (StockOrderBean stockOrderBean : orderBean1.orderList) {
//                    for (KDJOrderBean ziOrderBean : stockOrderBean.childOrderBeanList) {
//                        for (StockOrderBean orderBean : ziOrderBean.orderList) {
//                            if (orderBean.zhang) {
//                                orderZhang++;
//                            }
//                            if (orderBean.die) {
//                                orderDie++;
//                            }
//                            if (orderBean.pin) {
//                                orderPin++;
//                            }
//                            orderAvg = orderAvg + orderBean.average;
//                            count = count + orderBean.money;
//                            cishu++;
//                        }
//                    }
//                }
//            }
//            System.out.println();
//            System.out.println("买入涨 " + orderZhang + " 跌 " + orderDie + "  平 " + orderPin + " 胜率 " + (orderZhang / mOrderList.size()) * 100 + "%");
//            System.out.println("买入次数 " + cishu);
//            System.out.println("平均金额 " + (int) count / cishu);

        }


        System.out.println();
        System.out.println("行业买点 " + buyPointBeanList.size() + "个-------------------------------------");
        System.out.println();
        for (BuyPointBean pointBean : buyPointBeanList) {
            System.out.println("行业买点 " + pointBean.name + " " + pointBean.code + " " + pointBean.date);
//            System.out.println("周  j=" + pointBean.weekKdj.j + " k=" + pointBean.weekKdj.k + " d=" + pointBean.weekKdj.d);
//            System.out.println("日  j=" + pointBean.dayKdj.j + " k=" + pointBean.dayKdj.k + " d=" + pointBean.dayKdj.d);
            System.out.println("股价 " + pointBean.shouPan);
            System.out.println();
        }
        System.out.println("行业买点-------------------------------------");

//        System.out.println();
//        if (buyPointBeanList.size() > 0) {
//            index = 0;
//            findStock();
//        }

    }

    List<StockOrderBean> mOrderList = new ArrayList<>();
    List<Float> moneyList = new ArrayList<>();
    List<Integer> dealDayList = new ArrayList<>();
    List<ZhangDieBean> zhangDieBeans = new ArrayList<>();
    List<KDJOrderBean> industryOrderList = new ArrayList<>();
    List<BuyPointBean> buyPointBeanList = new ArrayList<>();

    Map<Integer, Float> chgMap = new HashMap<>();

    SimpleCallback simpleCallback = new SimpleCallback() {

        @Override
        public void fenxiCallback(int type) {
            if (type == 1) {
                testModel();
            }
        }

        @Override
        public void daBanCallback() {
            testModel();
        }

        @Override
        public void cghCallback(Map<Integer, Float> map, KDJOrderBean kdjOrderBean) {
            Iterator<Map.Entry<Integer, Float>> it1 = map.entrySet().iterator();
            while (it1.hasNext()) {
                Map.Entry<Integer, Float> entry = it1.next();
                Float value = map.get(entry.getKey());
                if (value == null) {
                    value = 0f;
                }
                value = value + entry.getValue();
                chgMap.put(entry.getKey(), value);
            }
            if (kdjOrderBean != null) {
                mOrderList.addAll(kdjOrderBean.orderList);
                industryOrderList.add(kdjOrderBean);
            }
            testModel();
        }

        @Override
        public void zhangDieCallback(ZhangDieBean zhangDieBean) {
            zhangDieBeans.add(zhangDieBean);
            testModel();
        }

        @Override
        public void kdjCallback(KDJOrderBean kdjOrderBean, BuyPointBean buyPointBean) {
            if (kdjOrderBean != null) {
                mOrderList.addAll(kdjOrderBean.orderList);
                industryOrderList.add(kdjOrderBean);
            }
            if (buyPointBean != null) {
                buyPointBeanList.add(buyPointBean);
            }
            testModel();
        }

        @Override
        public synchronized void pointCallback(List<StockOrderBean> orderList) {
            if (orderList != null && orderList.size() > 0) {
                mOrderList.addAll(orderList);
            }
            testModel();
        }


        @Override
        public void testModelNext(float money) {
            moneyList.add(money);
            testModel();
        }
    };

    public void getStockList(String url) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build();
        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, @NotNull okhttp3.Response response) throws IOException {
                if (response.body() != null) {
                    String html = response.body().string();
                    String tag1 = "\"diff\":";
                    int index1 = html.indexOf(tag1);
                    int index2 = html.lastIndexOf("}});");
                    html = html.substring(index1 + tag1.length(), index2);
                    List<FoundBean> bean = GsonUtil.parse(html, new TypeToken<List<FoundBean>>() {
                    }.getType());
                    foundList.addAll(bean);
                    start();
                }
            }
        });
    }
}
